package com.ebt.m.proposal_v2.retrofit;

import com.ebt.m.AppContext;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.UIHelper;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * @author archer.qi
 *         Created on 2017/5/18.
 */
public class RetrofitSubscriber<T> implements Observer<ResponseBodyBase<T>> {
    private OnResponseListener<T> callback;
    private boolean DEBUG;

    public RetrofitSubscriber(OnResponseListener<T> callback) {
        this.callback = callback;
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        String errorMsg = e == null ? "request fail, an error happened" : e.getMessage();
        Logger.e(errorMsg);
        showMsg("请求失败");
        if (errorMsg != null && errorMsg.startsWith("{\"code\":")) {
            // 服务端开发人员处理错误的方式：将错误信息包裹在Exception中抛出，所以会在onError接收到；这里将业务错误信息分发到正常途径
            ResponseError responseError = ErrorGenerator.parseErrorJson(errorMsg);
            if (responseError != null) {
                responseError.flag = 1;
            }
            callError(responseError);
            return;
        }
        callError(ErrorGenerator.requestError(errorMsg));
    }

    @Override
    public void onNext(ResponseBodyBase<T> responseBodyBase) {
        ResponseError error = responseBodyBase.error;
        T data = responseBodyBase.data;

        if (error != null) {
            Logger.e(error.toString());
            showMsg("请求失败");
            callError(error);
            return;
        }

        if (data == null) {
            error = ErrorGenerator.nullDataError();
            Logger.e(error.toString());
            showMsg("数据为空");
            callError(error);
            return;
        }

        showMsg("请求成功");
        callSuccess(data, responseBodyBase.paging);
    }


    private void callError(ResponseError error) {
        if (error == null) {
            error = ErrorGenerator.requestError();
        }
        if (callback != null) {
            callback.onFailure(error);
        }
    }

    private void callSuccess(T data, ResponsePage page) {
        if (callback != null) {
            callback.onSuccess(data, page);
        }
    }

    private void showMsg(String msg) {
        if (DEBUG) {
            UIHelper.makeToast(AppContext.getInstance(), msg);
        }
    }
}
